package com.ruoyi.cases.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.cases.domain.JlDailyStatistics;
import com.ruoyi.cases.domain.JlTroubleshootingTable;
import com.ruoyi.cases.service.IJlDailyStatisticsService;
import com.ruoyi.cases.utils.excel.ExcelExportToFileUrlComplex;
import com.ruoyi.cases.utils.excel.HexBeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cases.domain.JlStatisticsMouth;
import com.ruoyi.cases.service.IJlStatisticsMouthService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 月统计Controller
 * 
 * @author ruoyi
 * @date 2024-05-23
 */
@RestController
@RequestMapping("/cases/statisticsMouth")
public class JlStatisticsMouthController extends BaseController
{
    @Autowired
    private IJlStatisticsMouthService jlStatisticsMouthService;

    @Autowired
    private IJlDailyStatisticsService jlDailyStatisticsService;

    /**
     * 查询工区统计
     */
    @PreAuthorize("@ss.hasPermi('cases:statisticsDaily:list')")
    @GetMapping("/list")
    public TableDataInfo list(JlTroubleshootingTable jlTroubleshootingTable)
    {
        startPage();
        List<JlTroubleshootingTable> list = jlDailyStatisticsService.getMouthStatisticsList(jlTroubleshootingTable);
        return getDataTable(list);
    }

    /**
     * 导出月统计列表
     */
    @PreAuthorize("@ss.hasPermi('cases:statisticsMouth:export')")
    @Log(title = "月统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, JlStatisticsMouth jlStatisticsMouth)
    {
        List<JlStatisticsMouth> list = jlStatisticsMouthService.selectJlStatisticsMouthList(jlStatisticsMouth);
        ExcelUtil<JlStatisticsMouth> util = new ExcelUtil<JlStatisticsMouth>(JlStatisticsMouth.class);
        util.exportExcel(response, list, "月统计数据");
    }

    /**
     * 获取月统计详细信息
     */
    @PreAuthorize("@ss.hasPermi('cases:statisticsMouth:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(jlStatisticsMouthService.selectJlStatisticsMouthById(id));
    }

    /**
     * 新增月统计
     */
    @PreAuthorize("@ss.hasPermi('cases:statisticsMouth:add')")
    @Log(title = "月统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody JlStatisticsMouth jlStatisticsMouth)
    {
        return toAjax(jlStatisticsMouthService.insertJlStatisticsMouth(jlStatisticsMouth));
    }

    /**
     * 修改月统计
     */
    @PreAuthorize("@ss.hasPermi('cases:statisticsMouth:edit')")
    @Log(title = "月统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JlStatisticsMouth jlStatisticsMouth)
    {
        return toAjax(jlStatisticsMouthService.updateJlStatisticsMouth(jlStatisticsMouth));
    }

    /**
     * 删除月统计
     */
    @PreAuthorize("@ss.hasPermi('cases:statisticsMouth:remove')")
    @Log(title = "月统计", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(jlStatisticsMouthService.deleteJlStatisticsMouthByIds(ids));
    }


    /**
     * 月统计
     */
    @PreAuthorize("@ss.hasPermi('cases:statisticsMouth:export')")
    @Log(title = "工区统计", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTest")
    public void exportTest(HttpServletRequest request, HttpServletResponse response, JlTroubleshootingTable jlTroubleshootingTable)
    {
        List<JlTroubleshootingTable> list = jlDailyStatisticsService.getMouthStatisticsList(jlTroubleshootingTable);
        try{
            int xh = 1;
            Map model = new HashMap();
            Map<String,Long> dateMap =  list.stream().sorted(Comparator.comparing(JlTroubleshootingTable::getDealDate).reversed()).collect(Collectors.groupingBy(JlTroubleshootingTable::getDealDate,Collectors.counting()));
            /*填充excel下方结果用*/
            list.add(new JlTroubleshootingTable());
            list.add(new JlTroubleshootingTable());
            List<Map<String, Object>> listdata = new ArrayList<>();
            /*处理日合计数据*/
            Double perDayTotal =0.00;
            /*处理map排序*/
            dateMap = dateMap.entrySet().stream()
                    .sorted(Map.Entry.<String, Long>comparingByKey().reversed())
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            Map.Entry::getValue,
                            // 处理键冲突
                            (oldValue, newValue) -> oldValue,
                            () -> new TreeMap<>()
                    ));
            int times = 1;
            for(int x = 0; x<list.size()-2; x++){
                JlTroubleshootingTable  j = list.get(x);
                if(dateMap.get(j.getDealDate())==1){
                    j.setPerDayTotal(j.getCompletionCoefficient());
                    list.set(x,j);
                    times=1;
                }else{
                    perDayTotal += Double.parseDouble(j.getCompletionCoefficient());
                    if(dateMap.get(j.getDealDate())==times){
                        JlTroubleshootingTable item = list.get(x-times+1);
                        item.setPerDayTotal(String.format("%.2f",perDayTotal/times));
                        list.set(x-times+1,item);
                        perDayTotal = 0.00;
                        times = 0;
                    }
                    times++;
                }

            }

            for (JlTroubleshootingTable val: list) {
                val.setXh(xh);
                /*设置劳务形式合计*/
                val.setPersonTotal(String.valueOf(Integer.parseInt(val.getInsourcedNum()==null?"0":val.getInsourcedNum())+Integer.parseInt(val.getOutSourceNum()==null?"0":val.getOutSourceNum())));
                if(val.getInsourcedNum()==null || "".equals(val.getInsourcedNum())){
                    val.setInsourcedNum("0");
                }
                if(val.getOutSourceNum()==null || "".equals(val.getOutSourceNum())){
                    val.setOutSourceNum("0");
                }
                Map<String, Object> map = HexBeanUtils.object2Map(val);
                listdata.add(map);
                xh++;
            }

            String[][] upNoFrame1 = new String[initMapSize(dateMap)][5];
            int dateItem = 0 ;
            Long rowItem = 3L;
            for(String key : dateMap.keySet()){
                if(dateMap.get(key)>1){
                    upNoFrame1[dateItem] = new String[]{String.valueOf(rowItem),String.valueOf(rowItem-1+dateMap.get(key)),"17","17",""};
                    dateItem++;
                    rowItem  = rowItem+dateMap.get(key);
                }else{
                    rowItem++;
                }
            }
            String name ="xh,dealDate,deptName,type,type,type,quantitativeTypeName,locationNum,outSourceNum,insourcedNum,personTotal,insourcedName,qualifiedNum,quantitativeRatedUnitValue,perDay,quantitativeTypeValue,completionCoefficient,perDayTotal,auditResult,auditResult,assessorName,remark";
            /*名字弃用*/
            String[][] upNoFrame2 = {{"1","2","0","0","序号"},{"1","2","1","1","日期"},{"1","2","2","2","工区"},{"1","1","3","5","劳务形式"}
                    ,{"1","2","6","6","工作内容"},{"1","2","7","7","施工位置"},{"1","1","8","9","人数"},{"1","2","10","10","小计"},{"1","2","11","11","自有人员姓名"},{"1","2","12","12","完成总工程量"}
                    ,{"1","2","13","13","工程量单位"},{"1","2","14","14","平均每人工程量"},{"1","2","15","15","定量标准"},{"1","2","16","16","完成系数"},{"1","2","17","17","日均系数"},{"1","1","18","19","考核结果"}
            ,{"1","2","20","20","考核人"},{"1","2","21","21","备注"},{String.valueOf(list.size()+1),String.valueOf(list.size()+2),"14","16","月工区是否达标"},{String.valueOf(list.size()+1),String.valueOf(list.size()+2),"17","17","月工区考核结果"}};
            String[][] upNoFrame = concatenate2DStrings(upNoFrame1, upNoFrame2);

            model.put("excelTitleClos", name.split(",").length-1);
            model.put("fileName", "月统计");
            model.put("excelTitle",list.get(0).getDeptName() + "养护工区定额工作完成情况评价表（工区）");
            //[[行号,列号(&分隔),文字(&分隔),合并单元格(起始行,结束行,起始列,结束列)]]
            model.put("names", name.split(","));
            model.put("hbTitle", upNoFrame);
            model.put("excelTitleFontSize", "20");
            model.put("titles0",
                    new String[]{"养护工区定额工作完成情况评价表（个人）"});
            model.put("titles1",
                    new String[]{"序号", "日期", "工区", "劳务形式", "","","工作内容","施工位置","人数","","小计","自有人员姓名","完成总工程量","工程量单位","平均每人工程量","定量标准","完成系数","日均系数","考核结果","","考核人","备注"});
            model.put("titles2",
                    new String[]{"", "", "", "外包", "自主","自主+外包","","","外雇","自有","","","","","","定量标准","","","达标","未达标","",""});
            model.put("titleStarRows", 1);
            model.put("titleRows", 3);
            model.put("list", listdata);
            String columnWidth =
                    "0,15&1,30&2,20&3,20&4,25&5,25&6,40&7,25&8,25&9,25&10,25&11,50&12,25&13,25&14,25&15,25&16,25&17,25&18,25&19,25&20,25&21,25&22,25&23,25&24,25&25,25&26,50";
            model.put("columnWidth", columnWidth);
            new ExcelExportToFileUrlComplex().buildExcelDocument1(model, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int initMapSize(Map<String, Long> dateMap) {
        int returnNum = 0;
        for(String key:dateMap.keySet()){
            if(dateMap.get(key)>1){
                returnNum++;
            }
        }

        return returnNum;
    }

    private  String[][] concatenate2DStrings(String[][] array1, String[][] array2) {

        String[][] result = new String[array1.length+array2.length][];

        for (int i = 0; i < result.length; i++) {
            // 拼接每一行的String
            if(i<array1.length){
                result[i] = array1[i];
            }else{
                result[i] = array2[i-array1.length];
            }
        }
        return result;
    }

}
